package com.sicnu.cheer.leaugebar.wigets;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.sicnu.cheer.generalmodule.util.SharedPreferencesUtil;
import com.sicnu.cheer.generalmodule.util.StringUtils;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.leaugebar.R;
import com.sicnu.cheer.leaugebar.adapter.ShareAdapter;
import com.sicnu.cheer.leaugebar.bean.ShareBean;
import com.sicnu.cheer.leaugebar.bean.Update;
import com.sicnu.cheer.leaugebar.utils.QRCodeUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.system.text.ShortMessage;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * 分享页面
 * Created by cheer on 2017/3/14.
 */

public class SharePopupWindow extends PopupWindow implements View.OnClickListener, ShareAdapter.OnItemClickListener {
    private Context context;
    private SharePopupWindow mThis;
    private RecyclerView contentView;
    private ShareAdapter adapter;
    private View rootView;
    private List<ShareBean> data;


    public SharePopupWindow(Context context) {
        super(context);
        this.context = context;
        mThis = this;
        initShareSDK();
        initData();
        init();
    }

    /**
     * 初始化分享工具包
     */
    private void initShareSDK() {
        ShareSDK.initSDK(context, context.getString(R.string.share_app_key));
        HashMap<String, Object> QQPlatform = new HashMap<String, Object>();
        QQPlatform.put("Id", "1");
        QQPlatform.put("SortId", "1");
        QQPlatform.put("AppId", context.getString(R.string.qq_key));
        QQPlatform.put("ShareByAppClient", "true");
        QQPlatform.put("Enable", "true");
        ShareSDK.setPlatformDevInfo(QQ.NAME, QQPlatform);
        HashMap<String, Object> WXPlatform = new HashMap<String, Object>();
        WXPlatform.put("Id", "2");
        WXPlatform.put("SortId", "2");
        WXPlatform.put("AppId", context.getString(R.string.wx_key));
        WXPlatform.put("AppSecret", context.getString(R.string.wx_app_secret));
        WXPlatform.put("Enable", "true");
        ShareSDK.setPlatformDevInfo(Wechat.NAME, WXPlatform);
        HashMap<String, Object> SMSPlatform = new HashMap<String, Object>();
        SMSPlatform.put("Id", "3");
        SMSPlatform.put("SortId", "3");
        SMSPlatform.put("Enable", "true");
        ShareSDK.setPlatformDevInfo(ShortMessage.NAME, SMSPlatform);
    }


    /**
     * 初始化数据
     */
    private void initData() {
        data = new ArrayList<>();
        ShareBean bean = new ShareBean("微信", R.mipmap.share_wei_xin, ShareBean.ShareType.SHARE_TYPE_WE_CHAT);
        data.add(bean);
        bean = new ShareBean("QQ", R.mipmap.share_qq, ShareBean.ShareType.SHARE_TYPE_QQ);
        data.add(bean);
        bean = new ShareBean("短信", R.mipmap.share_msg, ShareBean.ShareType.SHARE_TYPE_SMS);
        data.add(bean);
        bean = new ShareBean("二维码", R.mipmap.share_qr_code, ShareBean.ShareType.SHARE_TYPE_QR_CODE);
        data.add(bean);
        bean = new ShareBean("复制链接", R.mipmap.share_copy_link, ShareBean.ShareType.SHARE_TYPE_LINK);
        data.add(bean);
    }

    /**
     * 初始化布局，展示分享方法
     */
    private void init() {
        rootView = LayoutInflater.from(context).inflate(R.layout.layout_share, null);
        rootView.setOnClickListener(this);
        rootView.findViewById(R.id.share_cancel).setOnClickListener(this);
        contentView = (RecyclerView) rootView.findViewById(R.id.share_content);
        setContentView(rootView);
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        setBackgroundDrawable(new ColorDrawable());
        setFocusable(true);
        adapter = new ShareAdapter(data);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        contentView.setLayoutManager(linearLayoutManager);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        contentView.addItemDecoration(new SelfItemDecoration());
        contentView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.share_cancel || v == rootView) {
            if (isShowing()) {
                dismiss();
            }
        }
    }

    /**
     * 二维码分享
     */
    private void qrCode() {
        File imagePath = context.getExternalFilesDir("image");
        File imageFile = new File(imagePath, "qrCode.png");
        Bitmap logo = BitmapFactory.decodeResource(context.getResources(), R.mipmap.app_logo);
        boolean isCreated = QRCodeUtil.createQRImage(getUrl(), 300, 300, logo, imageFile.getPath());
        if (isCreated) {
            View qrCodeView = LayoutInflater.from(context).inflate(R.layout.layout_qr_code, null);
            ImageView imageView = (ImageView) qrCodeView.findViewById(R.id.image);
            imageView.setImageBitmap(BitmapFactory.decodeFile(imageFile.getAbsolutePath()));
            imageView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    final Context context = v.getContext();
                    UIHelper.showDialog(context, "识别二维码", "二维码识别成功，是否前往打开", new UIHelper.DialogCallback() {
                        @Override
                        public void confirmCallBack() {
                            String url = getUrl();
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setData(Uri.parse(url));
                            context.startActivity(intent);
                        }

                        @Override
                        public void cancelCallBack() {

                        }
                    });
                    return true;
                }
            });
            AlertDialog alertDialog = new AlertDialog.Builder(context).setView(qrCodeView).create();
            alertDialog.setCanceledOnTouchOutside(true);
            alertDialog.show();
        }

    }

    private void copyLink() {
        ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("text", getUrl());
        clipboardManager.setPrimaryClip(clip);
        UIHelper.ToastMessage(context, "复制成功");
    }


    private String getUrl() {
        String url = SharedPreferencesUtil.getUserItem(mThis.getContentView().getContext(), "downloadUrl");
        if (url == null) {
            url = "网址异常";
        }
        return url;
    }

    @Override
    public void onItemClick(RecyclerView.Adapter adapter, int position) {
        if (adapter == this.adapter) {
            ShareBean item = data.get(position);
            int type = item.getType();
            Platform.ShareParams shareParams = new Platform.ShareParams();
            String content = "社团管理，让一切化繁为简， 活动展示  即时通讯  管理社团  社团风采";
            String title = "推荐您使用社团吧";
            String url = getUrl();
            if (type == ShareBean.ShareType.SHARE_TYPE_SMS) {
                content = content + url;
            }
            shareParams.setText(content);
            shareParams.setTitle(title);
            Platform platform = null;
            File appIcon = getAppIconFile();
            if (!appIcon.exists()) {
                saveAppIcon(appIcon);
            }
            if (type == ShareBean.ShareType.SHARE_TYPE_WE_CHAT) {
                platform = ShareSDK.getPlatform(Wechat.NAME);
                shareParams.setShareType(Platform.SHARE_WEBPAGE);
                shareParams.setImagePath(appIcon.getAbsolutePath());
                shareParams.setUrl(url);
            } else if (type == ShareBean.ShareType.SHARE_TYPE_QQ) {
                platform = ShareSDK.getPlatform(QQ.NAME);
                shareParams.setTitleUrl(url);
                shareParams.setImagePath(appIcon.getAbsolutePath());
            } else if (type == ShareBean.ShareType.SHARE_TYPE_SMS) {
                platform = ShareSDK.getPlatform(ShortMessage.NAME);
            } else if (type == ShareBean.ShareType.SHARE_TYPE_QR_CODE) {
                qrCode();
            } else if (type == ShareBean.ShareType.SHARE_TYPE_LINK) {
                copyLink();
            }
            if (platform != null) {
                platform.setPlatformActionListener(new PlatformActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        if (i == 0) {

                        }
                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        if (i == 0) {

                        }

                    }

                    @Override
                    public void onCancel(Platform platform, int i) {
                        if (i == 0) {

                        }

                    }
                });
                platform.share(shareParams);
            }
        }
    }


    private void saveAppIcon(File appIcon) {
        try {
            Bitmap bitmap = BitmapFactory.decodeResource(getContentView().getResources(), R.mipmap.app_logo);
            FileOutputStream outputStream = new FileOutputStream(appIcon);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            bitmap.recycle();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private File getAppIconFile() {
        File appIconDir = getContentView().getContext().getFileStreamPath("appIcon");
        if (!appIconDir.exists()) {
            appIconDir.mkdirs();
        }
        File appIcon = new File(appIconDir, "appIcon.png");
        return appIcon;
    }
}
